package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.model.Food;
import com.model.PO;
import com.model.User;
import com.service.FoodService;
import com.service.OrderService;
import com.service.UserService;
import com.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin("*")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private FoodService foodService;

    @Autowired
    private UserService userService;

    /**
     * 添加订单接口
     */
    @PostMapping("/orders")
    public Result addOrder(@RequestBody PO order) {
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        boolean save = orderService.save(order);
        if (save){
            return new Result("200","添加成功",1,null);
        } else {
            return new Result("500","添加失败,请联系管理员询问原因",0,null);
        }
    }

    /**
     * 根据ID删除订单接口
     */
    @DeleteMapping("/orders/{id}")
    public Result deleteOrderById(@PathVariable Integer id) {
        Boolean res = orderService.removeById(id);
        if (res){
            return new Result("200","删除成功",1,null);
        } else {
            return new Result("500","删除失败",0,null);
        }
    }

    /**
     * 根据用户 ID 查询用户订单
     * @param userId 用户 ID
     * @return 返回查询到的订单对象集合
     */
    @GetMapping("/orders/user/{userId}")
    public Result getOrderByUserId(@PathVariable("userId") Integer userId) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<PO> pos = orderService.list(new QueryWrapper<PO>().eq("user_id", userId));
        for (PO po : pos) {
            Map<String, Object> map = new HashMap<>();
            map.put("poId", po.getId());
            map.put("poStatus", po.getStatus());
            map.put("poCreateTime", po.getCreateTime());
            map.put("poUpdateTime", po.getUpdateTime());
            Food food = foodService.getById(po.getFoodId());
            map.put("foodName", food.getFoodName());
            map.put("foodStar", food.getStar());
            map.put("foodDesc", food.getFoodDesc());
            map.put("foodImgUrl", food.getImgUrl());
            map.put("foodType", food.getType());
            User user = userService.getById(po.getUserId());
            map.put("userName", user.getUserName());
            map.put("userAccount", user.getAccount());
            map.put("userPhone", user.getPhone());
            result.add(map);
        }
        return new Result("200","查询成功",result.size(), result);
    }

    /**
     * 根据 ID 查询订单
     * @param id 订单 ID
     * @return 返回查询到的订单对象
     */
    @GetMapping("/orders/{id}")
    public Result getOrderById(@PathVariable("id") Integer id) {
        List<Map<String, Object>> result = new ArrayList<>();
        PO order = orderService.getOne(new QueryWrapper<PO>().eq("id", id));
        Map<String, Object> map = new HashMap<>();
        map.put("poId", order.getId());
        map.put("poStatus", order.getStatus());
        map.put("poCreateTime", order.getCreateTime());
        map.put("poUpdateTime", order.getUpdateTime());
        Food food = foodService.getById(order.getFoodId());
        map.put("foodName", food.getFoodName());
        map.put("foodStar", food.getStar());
        map.put("foodDesc", food.getFoodDesc());
        map.put("foodImgUrl", food.getImgUrl());
        map.put("foodType", food.getType());
        User user = userService.getById(order.getUserId());
        map.put("userName", user.getUserName());
        map.put("userAccount", user.getAccount());
        map.put("userPhone", user.getPhone());
        result.add(map);
        return new Result("200","查询成功",result.size(), result);
    }

    /**
     * 查询单个订单接口
     */
    /*@GetMapping("/orders/{idOrUserIdOrFoodIdOrStatus}")
    public Result getOrderByIdOrUserIdOrFoodIdOrStatus(@PathVariable Object idOrUserIdOrFoodIdOrStatus) {
        QueryWrapper<PO> wrapper = new QueryWrapper<>();
        wrapper.and(i -> i.eq("id", idOrUserIdOrFoodIdOrStatus)
                .or()
                .eq("user_id", idOrUserIdOrFoodIdOrStatus)
                .or()
                .eq("food_id", idOrUserIdOrFoodIdOrStatus)
                .or()
                .eq("status", idOrUserIdOrFoodIdOrStatus));
        PO order = orderService.getOne(wrapper);
        return new Result("200","查询成功",1, List.of(order));
    }
*/

    /**
     * 查询全部订单接口
     */
    @GetMapping("/orders")
    public Result getAllOrders() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<PO> pos = orderService.list();
        for (PO po : pos) {
            Map<String, Object> map = new HashMap<>();

            map.put("poId", po.getId());
            map.put("poStatus", po.getStatus());
            map.put("poCreateTime", po.getCreateTime());
            map.put("poUpdateTime", po.getUpdateTime());
            Food food = foodService.getById(po.getFoodId());
            map.put("foodName", food.getFoodName());
            map.put("foodStar", food.getStar());
            map.put("foodDesc", food.getFoodDesc());
            map.put("foodImgUrl", food.getImgUrl());
            map.put("foodType", food.getType());

            User user = userService.getById(po.getUserId());
            map.put("userName", user.getUserName());
            map.put("userAccount", user.getAccount());
            map.put("userPhone", user.getPhone());

            result.add(map);
        }

        return new Result("200","查询成功",result.size(),result);
    }

    /**
     * 分页查询订单接口
     */
    @GetMapping("/orders/page/{pageNum}/{pageSize}")
    public IPage<PO> getOrdersByPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        Page<PO> page = new Page<>(pageNum, pageSize);
        return orderService.selectPage(page, null);
    }

    /**
     * 根据ID更新订单接口
     */
    @PutMapping("/orders/{id}")
    public Result updateOrderById(@PathVariable Integer id, @RequestBody PO order) {
        order.setId(id);
        order.setUpdateTime(new Date());
        Boolean res = orderService.updateById(order);
        if (res){
            return new Result("200","更新成功",1,List.of(order));
        } else {
            return new Result("500","更新失败",0,null);
        }
    }
}
